<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_medium'"
      :title="sysBusinessNumber.numberInformation"
      :append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-samplecategory-form"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :title="sysBusinessNumber.numberName"
          :label-width="formLabelWidth"
          prop="numberName"
          :error="errorMsg.numberName"
        >
          <el-input v-model="formData.numberName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          :title="sysBusinessNumber.numberType"
          :label-width="formLabelWidth"
          prop="numberType"
          :error="errorMsg.numberType"
        >
          <el-select
            v-model="formData.numberType"
            placeholder="请选择"
            @change="numberTypeChange"
          >
            <el-option
              v-for="item in numberTypeList"
              :key="item.value"
              :label="item.name"
              :value="Number(item.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :title="sysBusinessNumber.duplicateNumberVerification"
          :label-width="formLabelWidth"
          prop="verifyRepetition"
          :error="errorMsg.verifyRepetition"
        >
          <el-switch
            v-model="formData.verifyRepetition"
            :active-text="sysBusinessNumber.notVerifying"
            :inactive-text="sysBusinessNumber.verify"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          :title="sysBusinessNumber.numberingRules"
          style="width: 100%"
          :label-width="formLabelWidth"
        >
          <el-row
            v-for="(item, index) in formData.numberRuleList"
            :key="index"
            style="margin-bottom: 5px"
          >
            <el-col :span="6">
              <el-select
                v-model="formData.numberRuleList[index].numberRuleType"
                :placeholder="sysBusinessNumber.selectNumberingRuleType"
                @change="selchange(index)"
              >
                <el-option
                  v-for="items in numberRuleTypeList"
                  :key="items.value"
                  :disabled="
                    formData.numberType !== 10 &&
                    formData.numberType !== 20 &&
                    Number(items.value) === 4
                  "
                  :label="items.name"
                  :value="Number(items.value)"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-if="formData.numberRuleList[index].numberRuleType === 2"
                v-model="formData.numberRuleList[index].numberRuleContent"
                :placeholder="sysBusinessNumber.chooseDateFormat"
                @change="dateFormatChange(index)"
              >
                <el-option
                  v-for="items in dateFormatList"
                  :key="items.value"
                  :label="items.name"
                  :value="items.value"
                  :disabled="items.disabled"
                ></el-option>
              </el-select>

              <el-input
                v-else-if="formData.numberRuleList[index].numberRuleType === 1"
                v-model="formData.numberRuleList[index].numberRuleContent"
                :placeholder="sysBusinessNumber.enter"
                @change="estimate(index)"
              ></el-input>

              <el-input
                v-else-if="formData.numberRuleList[index].numberRuleType === 3"
                v-model="formData.numberRuleList[index].digit"
                :placeholder="sysBusinessNumber.enterNumberDigits"
                @keypress.native="numberInput"
                @change="digitChange(index)"
              ></el-input>

              <el-button
                v-else-if="formData.numberRuleList[index].numberRuleType === 4"
                type="primary"
                plain
                @click="addDepend(index)"
                >{{ sysBusinessNumber.addDependencyRelationship }}</el-button
              >
            </el-col>
            <el-col :span="8">
              <div v-if="formData.numberRuleList[index].numberRuleType === 2">
                {{ sysBusinessNumber.followDateRefreshFlow }}
                <el-switch
                  v-model="formData.numberRuleList[index].serialNumType"
                  :active-value="1"
                  :inactive-value="0"
                  @change="serialNumTypeChange(index)"
                ></el-switch>
              </div>
              <div
                v-else-if="formData.numberRuleList[index].numberRuleType === 4"
              >
                {{ sysBusinessNumber.followDependentObjectRefreshPipeline }}
                <el-switch
                  v-model="formData.numberRuleList[index].serialNumType"
                  :active-value="1"
                  :inactive-value="0"
                  @change="serialNumTypeChange(index)"
                ></el-switch>
              </div>

              <el-input
                v-else-if="formData.numberRuleList[index].numberRuleType === 3"
                v-model="formData.numberRuleList[index].numberRuleContent"
                :placeholder="sysBusinessNumber.enterStartingFlowNumber"
                @keypress.native="numberInput"
                @change="estimate(index)"
              ></el-input>
            </el-col>
            <el-col :span="4">
              <el-button
                type="danger"
                class="el-icon-minus"
                plain
                @click="removeList(index)"
              ></el-button>
            </el-col>
          </el-row>
          <div>
            <el-button
              type="primary"
              class="el-icon-plus"
              plain
              @click="addList"
            ></el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button
          type="primary"
          :disabled="!submitLoad"
          @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
      <ChoiceNumberDependDialog
        v-if="dialogFormVisibleDepend"
        ref="ChoiceNumberDependDialog"
        :depend-data.sync="dependData"
        :dialog-form-visible.sync="dialogFormVisibleDepend"
        @choiceDependCloes="choiceDependCloes"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  get,
  GetNumberType,
} from "../../../api/SysBusiness/SysBusinessNumber.js";
import { getDictList } from "../../../api/System/SystemDict";
import ChoiceNumberDependDialog from "./ChoiceNumberDependDialog.vue";
import _ from "lodash";

export default {
  name: "SysBusinessNumberEdit",
  components: { ChoiceNumberDependDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      submitLoad: true,
      dependData: [],
      dependIndex: 0,
      dialogFormVisibleDepend: false,
      // 刷新流水号状态
      refreshSerialNumberState: 0,
      // 用于存储选中的日期类型
      dateFormatArr: [],
      // 流水类型
      serialNumTypeList: [],
      // 日期格式
      dateFormatList: [],
      // 规则类型
      numberRuleTypeList: [],
      // 编号类型集合
      numberTypeList: [],
      loading: false,
      innerDialogFormVisible: false,
      formLabelWidth: "110px",
      initData: {
        id: 0,
        numberName: "",
        numberType: "",
        numberState: 0,
        numberRuleList: [],
      },
      formData: {
        id: 0,
        numberName: "",
        numberType: "",
        numberState: 0,
        verifyRepetition: 0,
        numberRuleList: [],
      },
      formDataRules: {
        numberName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        numberType: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
      },
      initErrorMsg: {
        numberName: "",
        numberType: "",
      },
      errorMsg: {
        numberName: "",
        numberType: "",
      },
    };
  },
  computed: {
    operateType() {
      return this.$t("ModuleSysBusiness.OperateType") || {};
    },
    sysBusinessNumber() {
      return this.$t("SysBusinessNumber") || {};
    },
  },
  watch: {
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    // 编号类型
    GetNumberType().then((res) => {
      this.numberTypeList = res.data;
    });
    // 编号类型
    // getDictList({ dictCode: "NumberType" }).then((res) => {
    //   this.numberTypeList = res.data;
    // });

    // 规则类型
    getDictList({ dictCode: "NumberRuleType" }).then((res) => {
      this.numberRuleTypeList = res.data;
    });

    // 日期格式
    getDictList({ dictCode: "DateFormat" }).then((res) => {
      this.dateFormatList = res.data;
      for (let i = 0; i < this.dateFormatList.length; i++) {
        this.dateFormatList[i].disabled = false;
      }
    });

    if (this.editId) {
      // 查询编号规则数据
      get({ id: this.editId }).then((res) => {
        this.formData = res.data;
      });
    }

    this.innerDialogFormVisible = this.dialogFormVisible;
  },
  methods: {
    choiceDependCloes(data) {
      this.formData.numberRuleList[this.dependIndex].dependData = data;
      this.dependData = [];
      this.dependIndex = -1;
    },
    // 添加依赖对象
    addDepend(index) {
      this.dependIndex = index;
      if (
        this.formData.numberRuleList[index].dependData !== null &&
        this.formData.numberRuleList[index].dependData !== undefined
      ) {
        this.dependData = JSON.parse(
          JSON.stringify(this.formData.numberRuleList[index].dependData)
        );
      }
      this.dialogFormVisibleDepend = true;
    },
    // 输入位数改变
    digitChange(index) {
      // 如果位数等于0默认改为1
      if (this.formData.numberRuleList[index].digit === 0) {
        this.formData.numberRuleList[index].digit = 1;
      }
      this.formData.numberRuleList[index].numberRuleContent = "";
      if (this.formData.numberRuleList[index].digit !== 0) {
        var record = 1;
        for (let i = 1; i <= this.formData.numberRuleList[index].digit; i++) {
          if (
            Number(record) === Number(this.formData.numberRuleList[index].digit)
          ) {
            this.formData.numberRuleList[index].numberRuleContent += "1";
          } else {
            this.formData.numberRuleList[index].numberRuleContent += "0";
          }
          record++;
        }
      }
    },
    numberInput: function(e) {
      // e.value = /[^\\d\\.]/.test(e.value)
      e.returnValue = /\d/.test(e.key);
    },
    // 随时间刷新流水状态
    serialNumTypeChange(index) {
      if (this.formData.numberRuleList[index].serialNumType === "0") {
        this.refreshSerialNumberState = 0;
      }

      if (this.refreshSerialNumberState !== 1) {
        if (this.formData.numberRuleList[index].serialNumType === "1") {
          this.refreshSerialNumberState = 1;
        }
      } else {
        this.$message.warning(
          this.$t("SysBusinessNumber.onlyFlowRefreshesDateOpened")
        );
        this.formData.numberRuleList[index].serialNumType = "0";
        return false;
      }
    },
    // 选择日期
    dateFormatChange(index) {
      this.dateFormatArr[index] =
        this.formData.numberRuleList[index].numberRuleContent;
      for (let i = 0; i < this.dateFormatList.length; i++) {
        this.dateFormatList[i].disabled = false;
      }
      for (let i = 0; i < this.dateFormatList.length; i++) {
        for (let o = 0; o < this.dateFormatArr.length; o++) {
          if (this.dateFormatArr[o] === this.dateFormatList[i].value) {
            this.dateFormatList[i].disabled = true;
          }
        }
      }
    },
    // 增加下拉框
    addList() {
      this.formData.numberRuleList.push({
        sysBusinessNumberId: 0,
        numberRuleType: "",
        numberRuleSort: 0,
        numberRuleContent: "",
        serialNumType: 0,
        // 位数
        digit: "",
      });
    },
    // 删除下拉框
    removeList(index) {
      if (Number(this.formData.numberRuleList[index].numberRuleType) === 2) {
        for (let i = 0; i < this.dateFormatList.length; i++) {
          if (
            this.dateFormatList[i].value ===
            this.formData.numberRuleList[index].numberRuleContent
          ) {
            this.dateFormatList[i].disabled = false;
          }
        }
      }
      this.formData.numberRuleList.splice(index, 1);
      // 移除日期
      this.dateFormatArr.splice(index, 1);
    },
    // 编号类型改变
    numberTypeChange() {
      if (this.formData.numberType !== 10 && this.formData.numberType !== 20) {
        for (let i = this.formData.numberRuleList.length - 1; i >= 0; i--) {
          if (this.formData.numberRuleList[i].numberRuleType === 4) {
            this.formData.numberRuleList.splice(i, 1);
          }
        }
      }
    },
    // 下拉框改变事件
    selchange(index) {
      if (
        this.formData.numberRuleList[index].numberRuleContent !== null &&
        this.formData.numberRuleList[index].numberRuleContent !== ""
      ) {
        this.serialNumberVerify(index);
      }
    },
    // 流水号验证
    serialNumberVerify(index) {
      const inputstr = this.formData.numberRuleList[index].numberRuleContent;
      if (this.formData.numberRuleList[index].numberRuleType === 3) {
        if (/[^0-9]/.test(inputstr)) {
          this.$message.error({
            title: this.$t("SysBusinessNumber.error"),
            message: this.$t("SysBusinessNumber.numberNegativeInteger"),
          });
          this.formData.numberRuleList[index].numberRuleContent = null;
          this.$forceUpdate();
          return false;
        }
      }
    },
    // 验证是否符合规则
    estimate(index) {
      if (this.formData.numberRuleList[index].numberRuleContent === 0) {
        this.formData.numberRuleList[index].numberRuleContent = 1;
      }
      this.formData.numberRuleList[index].digit =
        this.formData.numberRuleList[index].numberRuleContent.length;
    },
    cancel() {
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        if (
          this.formData.numberName === null ||
          this.formData.numberName === ""
        ) {
          this.$message.error({
            title: this.$t("SysBusinessNumber.error"),
            message: this.$t("SysBusinessNumber.enterNumberName"),
          });
          this.submitLoad = true;
          return false;
        }
        if (
          this.formData.numberRuleList === null ||
          this.formData.numberRuleList.length === 0
        ) {
          this.$message.error({
            title: this.$t("SysBusinessNumber.error"),
            message: this.$t("SysBusinessNumber.addNumberingRules"),
          });
          this.submitLoad = true;

          return false;
        }
        var o = 0;
        for (let i = 0; i < this.formData.numberRuleList.length; i++) {
          if (!this.formData.numberRuleList[i].numberRuleType) {
            this.$message.error({
              title: this.$t("SysBusinessNumber.error"),
              message: this.$t("SysBusinessNumber.addNumberingRules"),
            });
            this.submitLoad = true;

            return false;
          }
          if (this.formData.numberRuleList[i].numberRuleType === 4) {
            o++;
          }

          if (
            this.formData.numberRuleList[i].numberRuleType === "" ||
            this.formData.numberRuleList[i].numberRuleType === null
          ) {
            this.$message.error({
              title: this.$t("SysBusinessNumber.error"),
              message: this.$t("SysBusinessNumber.selectTypeNumberingRule"),
            });
            this.submitLoad = true;

            return false;
          }
          if (
            (this.formData.numberRuleList[i].numberRuleContent === "" ||
              this.formData.numberRuleList[i].numberRuleContent === null) &&
            this.formData.numberRuleList[i].numberRuleType !== 4
          ) {
            this.$message.error({
              title: this.$t("SysBusinessNumber.error"),
              message: this.$t("SysBusinessNumber.selectContentNumberingRule"),
            });
            this.submitLoad = true;

            return false;
          }
        }

        if (o > 1) {
          this.$message.error({
            title: this.$t("SysBusinessNumber.error"),
            message: this.$t(
              "SysBusinessNumber.dependencyRelationshipNumberingRule"
            ),
          });
          this.submitLoad = true;

          return false;
        }

        // 加排序
        for (let i = 0; i < this.formData.numberRuleList.length; i++) {
          this.formData.numberRuleList[i].numberRuleSort = Number(i);
        }

        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.loading = true;
            this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
            if (this.formData.id <= 0) {
              create(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.submitLoad = true;

                    this.closeDialog();
                  } else {
                    this.submitLoad = true;

                    this.showValidateMsgCheck(res);
                  }
                  this.loading = false;
                })
                .catch(() => {
                  this.loading = false;
                });
            } else {
              update(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.submitLoad = true;

                    this.closeDialog();
                  } else {
                    this.submitLoad = true;

                    this.showValidateMsgCheck(res);
                  }
                  this.loading = false;
                })
                .catch(() => {
                  this.loading = false;
                });
            }
          } else {
            this.submitLoad = true;

            return false;
          }
        });
      }
    }, 2000),
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("numberName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("numberType", this.errorMsg, res.msg);
      }
    },
  },
};
</script>

<style scoped>
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}
</style>
